package com.fightingFish.user.servlet;

import com.fightingFish.user.bean.Anchor;
import com.fightingFish.user.bean.Record;
import com.fightingFish.user.bean.User;
import com.fightingFish.user.service.impl.AnchorServiceImpl;
import com.fightingFish.user.service.impl.UserServiceImpl;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/userInfo")
public class PersonCenterServlet extends HttpServlet {

    private AnchorServiceImpl asi = new AnchorServiceImpl();
    private UserServiceImpl usi = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        String methodName = req.getParameter("methodName");
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 通过用户ID查询用户个人信息
     */
    protected void selectInfoByUserId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("selectInfoByUserId");
        int userId = 0;
        try {
            userId = Integer.parseInt(req.getParameter("loginUser"));
        } catch (Exception e) {
        }
        if (userId == 0) {
            JSONObject json = new JSONObject();
            json.put("result", "未登陆");
        }
        User user = usi.selectInfoByid(userId);
        JSONObject json = JSONObject.fromObject(user);
        resp.getWriter().print(json);
    }

    /**
     * 通过用户id找到该用户充值鱼币
     * 返回一个充值后的金额
     */
    protected void rechargeBalance(HttpServletRequest req, HttpServletResponse resp) {
         User u=(User)req.getSession().getAttribute("loginUser");
         Double money=0.0;
         try {
             money= Double.valueOf(req.getParameter("money"));
         }catch (Exception e){}
         if(money>0) {
             Double newMoney = new UserServiceImpl().rechargeBalance(u.getUserId(), money);
             try {
                 resp.sendRedirect(req.getContextPath() + "/anchorSearch?methodName=queryAttentionAnchor");
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }else{
             try {
                 resp.sendRedirect(req.getContextPath() + "/anchorSearch?methodName=queryAttentionAnchor");
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
    }

    /**
     * 通过用户id找到该用户的消费记录
     */
    protected void selectRecordByid(HttpServletRequest req, HttpServletResponse resp) {
        Integer anchorid=0;
        try {
            anchorid = Integer.valueOf(req.getParameter("anchorid"));
        }catch (Exception e){

        }
        ArrayList<Record> arrayListRecord = new UserServiceImpl().selectRecordByid(anchorid);
        JSONArray json = JSONArray.fromObject(arrayListRecord);
        try {
            resp.getWriter().print(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过主播id查询主播的个人信息
     */
    protected void selectInfoByAnchorId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int anchorId = Integer.parseInt(req.getParameter("anchorId"));
        Anchor anchor = asi.selectInfoByAnchorId(anchorId);
        System.out.println(anchor);
        JSONObject json = JSONObject.fromObject(anchor);
        resp.getWriter().print(json);

    }

    /**
     * 通过主播id遍历当前主播间的全部粉丝信息
     */
    protected void selectAllByAnchor(HttpServletRequest req, HttpServletResponse resp) {
//        System.out.println("selectAllByAnchor");
        Integer anchorId=0;
        try {
            anchorId = Integer.valueOf(req.getParameter("anchorId"));
        }catch (Exception e){

        }
        ArrayList<User> userlist = asi.selectAllByAnchor(anchorId);
//        for(User u:userlist){
//            System.out.println("粉丝:"+u.toString());
//        }
        JSONArray json=JSONArray.fromObject(userlist);
        try {
            resp.getWriter().print(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 前端主播编辑信息
     * 主播可以通过主播id修改个人的信息
     * （密码，头像，昵称，性别，个性签名，手机号，邮箱）
     * （房间名，直播类型，直播间封面）
     */
    protected void updateInfoByAnchorId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int anchorid=((User)req.getSession().getAttribute("loginUser")).getUserId();
        Anchor a=new AnchorServiceImpl().selectInfoByAnchorId(anchorid);
        String sex=req.getParameter("sex");
        if("man".equals(sex)){
            sex="男";
        }else {
            sex="女";
        }
        String nickName = req.getParameter("nickName");
        String phone = req.getParameter("telephone1");
        String email = req.getParameter("email1");
        Boolean flag = asi.updateInfoByAnvhorid(anchorid,nickName,sex ,a.getSignInfo() , phone, email);
        if(flag){
            resp.sendRedirect(req.getContextPath()+"/anchorSearch?methodName=queryAttentionAnchor");
        }
    }

    /**
     * 用户签到
     * @param req
     * @param resp
     * @throws IOException
     */
    protected void signDay(HttpServletRequest req, HttpServletResponse resp)throws IOException {
        int userId=((User)req.getSession().getAttribute("loginUser")).getUserId();
       if(new UserServiceImpl().signDay(userId)) {
           resp.sendRedirect(req.getContextPath() + "/anchorSearch?methodName=queryAttentionAnchor");
       }
    }

}
